package com.megvii.corelib.update;

import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by linyue on 16/3/4.
 */
public class UpdateUtil
{
    public static HttpURLConnection createConnection(String urlString)
    {
        return createConnection(urlString, 0);
    }

    public static HttpURLConnection createConnection(String urlString, int rangeStart)
    {
        try
        {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(false);
            connection.setConnectTimeout(10 * 1000);
            connection.setReadTimeout(10 * 1000);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            if (rangeStart > 0)
            {
                connection.setRequestProperty("Range", "bytes=" + rangeStart + "-");
            }
            connection.connect();
            return connection;
        }
        catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static int getFileSize(String fileName)
    {
        File file = getFile(fileName);
        int size = 0;
        if (file.exists())
        {
            size = (int) file.length();
        }
        return size;
    }

    public static File getFile(String fileName)
    {
        return new File(Environment.getExternalStorageDirectory(), fileName);
    }

    public static void deleteFile(String fileName)
    {
        File file = UpdateUtil.getFile(fileName);
        if (file.exists())
        {
            file.delete();
        }
    }

    public static long getFreeSpace()
    {

        StatFs statFs = new StatFs(Environment.getExternalStorageDirectory()
                .getAbsolutePath());
        //sd卡分区数
        long blockCounts = statFs.getBlockCount();
        //sd卡可用分区数
        long avCounts = statFs.getAvailableBlocks();
        //一个分区数的大小
        long blockSize = statFs.getBlockSize();
        //sd卡可用空间
        long spaceLeft = avCounts * blockSize;
        return spaceLeft;
    }

    public static boolean isSpaceEnough(long spaceNeeded)
    {
        return spaceNeeded < getFreeSpace();
    }
}
